package com.union.vehicleassistant.adapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import java.util.Arrays;
import java.util.List;

/**
 * @author CuiZhen
 * @date 2019/5/11
 * GitHub: https://github.com/goweii
 */
public class FixedFragmentPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> mFragments = null;
    private List<String> mTitles = null;

    public void setFragmentList(Fragment... fragments) {
        this.mFragments = Arrays.asList(fragments);
        notifyDataSetChanged();
    }

    public void setFragmentList(List<Fragment> fragments) {
        this.mFragments = fragments;
        notifyDataSetChanged();
    }

    public void setTitles(String... titles) {
        mTitles = Arrays.asList(titles);
    }

    public void setTitles(List<String> titles) {
        mTitles = titles;
    }

    public FixedFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @NonNull
    @Override
    public Fragment getItem(int i) {
        return mFragments.get(i);
    }

    @Override
    public int getCount() {
        return mFragments == null ? 0 : mFragments.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        if (mTitles != null && mTitles.size() == getCount()) {
            return mTitles.get(position);
        }
        Fragment fragment = mFragments.get(position);
        if (fragment instanceof PageTitle) {
            PageTitle pageTitle = (PageTitle) fragment;
            return pageTitle.getPageTitle();
        }
        return "";
    }

    public interface PageTitle {
        CharSequence getPageTitle();
    }
}
